package com.google.untils.communicate;

import net.sf.json.JSONObject;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Iterator;

@Component
public class HttpControl {
    private static final Logger logger = LoggerFactory.getLogger(HttpControl.class);

    @Resource
    HttpClientBuilder httpClientBuilder;
    
    private URI BuildURI(String RemoteServiceUrl) throws URISyntaxException
    {
        URIBuilder uri = new URIBuilder(RemoteServiceUrl);
        return uri.build();
    }

    private URI BuildURI_KeyValue(String RemoteServiceUrl, Object O) throws URISyntaxException
    {
        JSONObject data = (JSONObject) O;
        URIBuilder uri = new URIBuilder(RemoteServiceUrl);
        Iterator<String> it = data.keys();
        while (it.hasNext())
        {
            String key = it.next();
            uri.addParameter(key, data.getString(key));
        }
        return uri.build();
    }

    private URI BuildURI_Path(String RemoteServiceUrl, Object O) throws URISyntaxException
    {
        JSONObject data = (JSONObject) O;
        StringBuffer sb = new StringBuffer();
        String[] pathParam = RemoteServiceUrl.split("/\\{");
        for (int i = 0; i < pathParam.length; i++)
        {
            if (pathParam[i].endsWith("}"))
            {
                String key = pathParam[i].replace("}", "");
                pathParam[i] = "/" + data.getString(key);
                data.remove(key);
            }
            sb.append(pathParam[i]);
        }
        URIBuilder uri = new URIBuilder(sb.toString());
        Iterator<String> it = data.keys();
        while (it.hasNext())
        {
            String key = it.next();
            String value = data.getString(key);
            uri.addParameter(key, value);
        }

        return uri.build();
    }

    private String SendPost(URI uri) throws Exception
    {
        String result = null;

        HttpPost post = new HttpPost(uri);

        CloseableHttpClient httpClient = httpClientBuilder.getHttpClient();
        CloseableHttpResponse response = null;
        try
        {
            response = httpClient.execute(post);
            result = httpClientBuilder.getContent(response);
            return result;
        } catch (Exception e)
        {
            e.printStackTrace();
            logger.error("调用远程服务异常：" + e);
            throw e;
        } finally
        {
            try
            {
                if (response != null) response.close();
            } catch (IOException e)
            {
                logger.error("HttpClient关闭异常:", e);
            }
        }
    }


    private String SendGet(URI uri) throws Exception
    {
        String result = null;

        HttpGet get = new HttpGet(uri);

        CloseableHttpClient httpClient = httpClientBuilder.getHttpClient();
        CloseableHttpResponse response = null;
        try
        {
            response = httpClient.execute(get);
            result = httpClientBuilder.getContent(response);
            return result;
        } catch (Exception e)
        {
            e.printStackTrace();
            logger.error("调用远程服务异常：" + e);
            throw e;
        } finally
        {
            try
            {
                if (response != null) response.close();
            } catch (IOException e)
            {
                logger.error("HttpClient关闭异常:", e);
            }

        }
    }

    private String SendJSON(URI uri, Object data) throws Exception
    {
        String result = null;

        HttpPost post = new HttpPost(uri);
        post.setHeader("Content-Type", "application/json");
        post.setEntity(new StringEntity(data.toString(), "UTF-8"));

        CloseableHttpClient httpClient = httpClientBuilder.getHttpClient();
        CloseableHttpResponse response = null;
        try
        {
            response = httpClient.execute(post);
            result = httpClientBuilder.getContent(response);
            return result;
        } catch (IOException e)
        {
            e.printStackTrace();
            logger.error("调用远程服务异常：" + e);
            throw e;
        } finally
        {
            try
            {
                if (response != null) response.close();
            } catch (IOException e)
            {
                logger.error("HttpClient关闭异常:", e);
            }
        }
    }

}
